<script setup lang="ts">
import { ref, computed } from "vue";
import { useColumns } from "./columns";
import "plus-pro-components/es/components/search/style/css";
import { PlusSearch, type PlusColumn } from "plus-pro-components";
import { ElMessage, ElMessageBox } from "element-plus";
import { addDialog } from "@/components/ReDialog";
import dialogForms, { type FormProps } from "./handle.vue";
import { meetingRefund, getMeetingBuyList } from "@/api/meeting";
import { utils, writeFile } from "xlsx";
import { formatDate, canMeetingFundBack } from "@/utils/common";
import { useRoute } from "vue-router";
defineOptions({
  name: "OperateTourBuy"
});
import { useMenu } from "@/utils/power";
const userDetailMap = {
  u_name: "姓名",
  u_mobile: "手机",
  u_address: "地址"
};
const power = useMenu(["exportExcel", "handle"]);
const route = useRoute();
const aoId = Number(route.query.id);
const tableRef = ref();
const multipleSelection = ref([]);
const toggleSelection = (rows?: any) => {
  const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
  if (rows) {
    rows.forEach(row => {
      toggleRowSelection(row, undefined);
    });
  } else {
    clearSelection();
  }
};

const searchColumns: PlusColumn[] = [
  {
    label: "搜索",
    width: 200,
    prop: "keyWord",
    valueType: "copy",
    tooltip: "请输入搜索关键词"
  },
  {
    label: "账号",
    width: 200,
    prop: "account",
    valueType: "copy",
    tooltip: "请输入用户账号"
  },
  {
    label: "用户ID",
    width: 200,
    prop: "uId",
    valueType: "input-number",
    fieldProps: {
      controls: false
    },
    tooltip: "请输入搜索用户ID"
  }
];

const {
  loading,
  columns,
  dataList,
  pagination,
  loadingConfig,
  adaptiveConfig,
  params,
  loadData,
  onSizeChange,
  onKeywordChange,
  onCurrentChange
} = useColumns(aoId);
const columnsRef = computed(() => {
  if (power.value.handle) {
    return columns;
  }
  const columnsCopy = [...columns];
  return columnsCopy.slice(0, -1);
});

const handleSearch = (value: any) => {
  console.log(value, "search");
  onKeywordChange(value);
};
const handleReset = value => {
  console.log("reset", value);
  onKeywordChange(value);
};
const handleChange = (value: any, target: any) => {
  console.log("change", value);
  if (
    target.prop == "keyWord" ||
    target.prop == "uId" ||
    target.prop == "account"
  ) {
    return;
  }
  onKeywordChange(value);
};

const handleSelectionChange = selection => {
  multipleSelection.value = selection;
};
function doClick(rows?) {
  console.log(
    "%crow===详情>>>: ",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    rows
  );

  if (rows.length <= 0) {
    ElMessage.error("请选择报名信息");
    return;
  }
  ElMessageBox.confirm("确认退款取消报名吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await meetingRefund({
        buyIds: rows?.map(v => v.buyId) ?? []
      })
        .then(res => {
          const ids = res.data;
          if (ids && ids.length > 0) {
            const idStr = ids.join(",");
            ElMessageBox.alert(`编号${idStr}处理失败，请联系管理员`, "提示", {
              confirmButtonText: "确定",
              type: "info"
            });
          }
          loadData();
          ElMessage.success("处理成功");
        })
        .catch(e => {});
    })
    .catch(e => {});
}
const fullscreenLoading = ref(false);

const exportExcel = async () => {
  try {
    const postData = Object.assign({}, params.value);
    postData.pageSize = 5000;
    postData.page = 1;
    const resData = await getMeetingBuyList(postData);
    const data = resData.data.items;

    const dataKeys: string[] = [
      "meetingTitle",
      "acName",
      "payType",
      "account",
      "uDetails",
      "pricePoint",
      "expTime",
      "auState"
    ];
    const titleList: string[] = [
      "旅游名称",
      "活动场次",
      "支付方式",
      "报名账户",
      "报名详情",
      "金额",
      "过期时间",
      "状态"
    ];
    const mapPayType = ["余额", "收益", "积分", "消费券"];
    const mapAuState = [
      "待支付",
      "待使用",
      "已使用",
      "退款售后中",
      "退款售后完成",
      "驳回"
    ];
    const res: string[][] = data.map(item => {
      const arr = [];
      dataKeys.forEach(column => {
        if (column === "payType") {
          arr.push(mapPayType[item[column]]);
        } else if (column === "uDetails") {
          const detail = JSON.parse(item[column]);
          const ds = [];
          for (const key in detail) {
            if (userDetailMap[key]) {
              ds.push(`${userDetailMap[key]}:${detail[key]}`);
            }
          }
          arr.push(ds.join(","));
        } else if (column === "auState") {
          arr.push(mapAuState[item[column]]);
        } else {
          arr.push(item[column]);
        }
      });
      return arr;
    });
    res.unshift(titleList);
    const workSheet = utils.aoa_to_sheet(res);
    const workBook = utils.book_new();
    utils.book_append_sheet(workBook, workSheet, "数据报表");
    writeFile(workBook, `${formatDate(new Date())} 旅游报名报表.xlsx`);
    ElMessage.success(`导出成功${data.length}条`);
  } catch (error) {
    console.log(error, "exportError");
  }
};
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>旅游报名</h3>
        </template>
        <template v-if="power.exportExcel" #extra>
          <el-popconfirm
            title="是否确认导出(默认导出最大5000条数据)"
            @confirm="exportExcel"
          >
            <template #reference>
              <el-button
                v-loading.fullscreen.lock="fullscreenLoading"
                type="primary"
                size="default"
                class="mb-4!"
              >
                导出Excel
              </el-button>
            </template>
          </el-popconfirm>
        </template>
        <PlusSearch
          class="mt-5"
          :columns="searchColumns"
          :hasUnfold="false"
          @reset="handleReset"
          @change="handleChange"
          @search="handleSearch"
        />
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :fit="true"
      :adaptiveConfig="adaptiveConfig"
      row-key="buyId"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columnsRef"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @page-size-change="onSizeChange"
      @page-current-change="onCurrentChange"
    >
      <template #banner="{ row, index }">
        <el-image
          preview-teleported
          loading="lazy"
          :src="row.banner"
          :preview-src-list="dataList.map(v => v.banner)"
          :initial-index="index"
          fit="cover"
          class="w-[50px] h-[50px]"
        />
      </template>
      <template #detail="{ row }">
        <el-descriptions :column="1">
          <template v-if="row.uDetails">
            <template
              v-for="(value, key) in JSON.parse(row.uDetails)"
              :key="key"
            >
              <el-descriptions-item :label="userDetailMap[key]">{{
                value || "-"
              }}</el-descriptions-item>
            </template>
          </template>
        </el-descriptions>
      </template>
      <template v-if="power.handle" #operation="{ row }">
        <el-button
          v-if="canMeetingFundBack(row)"
          link
          type="primary"
          size="small"
          @click="doClick([row])"
        >
          退款
        </el-button>
      </template>
    </pure-table>

    <div v-if="power.handle" style="margin-top: 20px">
      <el-button
        @click="toggleSelection(dataList.filter(v => canMeetingFundBack(v)))"
        >全选</el-button
      >
      <el-button @click="toggleSelection()">取消所有</el-button>
      <el-button @click="doClick(multipleSelection)">处理所选</el-button>
    </div>
  </ElCard>
</template>

<style scoped>
:deep(.el-descriptions),
:deep(.el-descriptions__table tr) {
  --el-card-bg-color: transparent !important;
  --el-fill-color-blank: transparent !important;
  background: transparent !important;
}
.wrap-text {
  white-space: normal !important; /* 允许自动换行 */
  word-break: break-all; /* 强制换行 */
}
</style>
